package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.mapper.BaseCategory1Mapper;
import com.atguigu.tingshu.album.mapper.BaseCategory2Mapper;
import com.atguigu.tingshu.album.mapper.BaseCategory3Mapper;
import com.atguigu.tingshu.album.mapper.BaseCategoryViewMapper;
import com.atguigu.tingshu.album.service.BaseCategoryService;
import com.atguigu.tingshu.common.anno.GuiGuCache;
import com.atguigu.tingshu.model.album.BaseCategory1;
import com.atguigu.tingshu.model.album.BaseCategory2;
import com.atguigu.tingshu.model.album.BaseCategory3;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.atguigu.tingshu.vo.album.AlbumCategoryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class BaseCategoryServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1> implements BaseCategoryService {

	@Autowired
	private BaseCategoryViewMapper baseCategoryViewMapper;
	@Autowired
	private BaseCategory3Mapper baseCategory3Mapper;
	@Autowired
	private BaseCategory2Mapper baseCategory2Mapper;

	@Override
	public List<AlbumCategoryVo> findAllCategory() {
		return baseCategoryViewMapper.findAllCategory();
	}



	// 加入了查询缓存的功能，并且使用了分布式锁解决了缓存击穿问题
	@GuiGuCache(
			cacheKey = "album:category:view:" + "#{#params[0]}" ,
			enableLock = true ,
			lockName = "album:category:view:lock:" + "#{#params[0]}"
	)
	@Override
	public BaseCategoryView findByCategoryBy3Id(Long category3id) {
		BaseCategoryView baseCategoryView = baseCategoryViewMapper.selectById(category3id);
		return baseCategoryView ;
	}

	@Override
	public AlbumCategoryVo getBaseCategoryList(Long category1Id) {

		return baseCategoryViewMapper.getCategoryInfoByCategory1Id(category1Id);
	}

	@Override
	public List<BaseCategory3> findTopBaseCategory3(Long categort1Id) {
		//根据一级分类id查询二级分类集合
		LambdaQueryWrapper<BaseCategory2> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(BaseCategory2::getCategory1Id, categort1Id);
		List<BaseCategory2> baseCategory2List = baseCategory2Mapper.selectList(lambdaQueryWrapper);
		List<Long> category2IdList = baseCategory2List.stream().map(BaseCategory2::getId).collect(Collectors.toList());

		//	查询置顶消息
		LambdaQueryWrapper<BaseCategory3> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
		// last("limit 7") 查询前7条
		lambdaQueryWrapper3.in(BaseCategory3::getCategory2Id,category2IdList).eq(BaseCategory3::getIsTop,1).last("limit 7");

		// 查询数据返回结果
		return baseCategory3Mapper.selectList(lambdaQueryWrapper3);
	}
}
